package com.sz.app.oss.api.common.csr;

import com.sz.app.oss.constants.Permissions;
import com.sz.biz.csr.dto.CsrWorkOrderSchemaSaveDto;
import com.sz.biz.csr.dto.CsrWorkOrderTransactionDto;
import com.sz.biz.csr.service.CsrWorkOrderSchemaService;
import com.sz.biz.csr.service.CsrWorkOrderTransactionService;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.MessagesCodes;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by xutao on 17/5/20.
 */
@RestController
@RequestMapping("/api/v1/csrworkorder")
@Api(description = " ", tags = "040-002、客服-工单")
public class CsrWorkOrderController extends BaseController {

    @Autowired
    CsrWorkOrderSchemaService csrWorkOrderSchemaService;

    @Autowired
    CsrWorkOrderTransactionService csrWorkOrderTransactionService;

    @Autowired
    CustomerUserService customerUserService;

    /**
     * 工单查询主页
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "工单主页查询", notes = "工单主页查询，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sortName", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "workOrderCode", value = "工单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "creator", value = "创建者ID", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerUserId", value = "客户ID", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "工单状态：0:已创建 1：处理中 2：已解决 3：已关闭", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerName", value = "客户姓名", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "blockOrder", value = "是否为阻塞订单", required = false, dataType = "boolean", paramType = "query")
    })
    @RequestMapping(value = "/search", method = {RequestMethod.GET})
    public QResultDto getOperationPointList(@RequestParam(defaultValue = "workOrderCode") String sortName,
                                            @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                            @RequestParam(required = false, defaultValue = "false") boolean blockOrder,
                                            @RequestParam(defaultValue = "1") int pageIndex,
                                            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                            @RequestParam(required = false) String beginTime,
                                            @RequestParam(required = false) String endTime,
                                            @RequestParam(required = false) String workOrderCode,
                                            @RequestParam(required = false) String title,
                                            @RequestParam(required = false, defaultValue = "0") int creator,
                                            @RequestParam(required = false, defaultValue = "0") int customerUserId,
                                            @RequestParam(required = false, defaultValue = "0") int status,
                                            @RequestParam(required = false) String customerName) throws BizException {

        workOrderCode = StringUtils.replaceSqlPattern(workOrderCode);
        title = StringUtils.replaceSqlPattern(title);
        beginTime = StringUtils.replaceSqlPattern(beginTime);
        endTime = StringUtils.replaceSqlPattern(endTime);
        customerName = StringUtils.replaceSqlPattern(customerName);
        sortName = StringUtils.replaceSqlPattern(sortName);

        if (StringUtils.isEmpty(workOrderCode)) {
            workOrderCode = null;
        }

        if (StringUtils.isEmpty(title)) {
            title = null;
        }

        if (StringUtils.isEmpty(beginTime)) {
            beginTime = null;
        }

        if (StringUtils.isEmpty(endTime)) {
            endTime = null;
        }

        if (StringUtils.isEmpty(customerName)) {
            customerName = null;
        }

        if (StringUtils.isEmpty(sortName)) {
            sortName = null;
        }

        Date beginDate = null;
        Date endDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (beginTime != null && !"".equalsIgnoreCase(beginTime)) {
            try {
                beginDate = sdf.parse(beginTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (endTime != null && !"".equalsIgnoreCase(endTime)) {
            try {
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (workOrderCode != null && !"".equals(workOrderCode)) {
            creator = 0;
            customerUserId = 0;
            beginDate = null;
            endDate = null;
            title = null;
            status = -1;
            customerName = null;
        }

        QResultDto qResultDto = csrWorkOrderSchemaService.findWorkOrderList(pageIndex, pageSize, sortName, isAsc, workOrderCode, creator, customerUserId, beginDate, endDate, title, status, customerName, blockOrder);

        return qResultDto;
    }

    /**
     * 凭借ID查找工单详细信息
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "凭借ID查找工单详细信息", notes = "凭借ID查找工单详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单主ID ", required = true, dataType = "int", paramType = "path")})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_WORK_ORDER)
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public QResultDto findDetailInfoById(@PathVariable int id) {

        QResultDto qResultDto = csrWorkOrderSchemaService.findDetailInfoById(id);

        return qResultDto;
    }

    /**
     * 处理工单
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "处理工单", notes = "处理工单")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_WORK_ORDER)
    @RequestMapping(value = "/progressing", method = {RequestMethod.POST})
    public ResultDto transactionWorkOrder(@RequestBody @Validated CsrWorkOrderTransactionDto csrWorkOrderTransactionDto) throws Exception {
        int id = csrWorkOrderTransactionService.save(csrWorkOrderTransactionDto);
        ResultDto qResultDto = getOperateSuccessDto(MessagesCodes.MODULE_TRANSACTION_WORK_ORDER_SUCCESS);
        qResultDto.setData(id);
        return qResultDto;
    }

    /**
     * 新增工单
     */
    @ApiOperation(value = "新增工单", notes = "新增工单")
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public ResultDto addWorkOrder(@RequestBody @Validated CsrWorkOrderSchemaSaveDto csrWorkOrderSchemaSaveDto) throws Exception {
        int id = csrWorkOrderSchemaService.save(csrWorkOrderSchemaSaveDto);
        ResultDto qResultDto = getOperateSuccessDto(MessagesCodes.MODULE_WORK_ORDER_CREATE_SUCCESS);
        qResultDto.setData(id);
        return qResultDto;
    }

    /**
     * 获取工单类型列表
     */
    @ApiOperation(value = "获取工单类型列表", notes = "获取工单类型列表")
    @RequestMapping(value = "/typelist", method = {RequestMethod.GET})
    public QResultDto addWorkOrder() throws Exception {

        QResultDto qResultDto = csrWorkOrderSchemaService.getWorkOrderTypeList();

        return qResultDto;
    }

    /**
     * 删除工单
     *
     * @param listId
     * @throws Exception
     */
    @ApiOperation(value = "删除工单", notes = "删除工单")
    @ApiImplicitParam(name = "listId", value = "工单ID", required = true, dataType = "List", paramType = "body")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_WORK_ORDER)
    @RequestMapping(value = "deletions", method = {RequestMethod.POST})
    public QResultDto deleteExchangeRate(@RequestBody List<Integer> listId) {

        csrWorkOrderSchemaService.batchDelete(listId);

        QResultDto qResultDto = new QResultDto();

        qResultDto.setMsg("删除工单成功！");

        return qResultDto;
    }

    /**
     * 获取工单客户列表
     */
    @ApiOperation(value = "获取工单客户列表", notes = "获取工单客户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/usernamelist", method = {RequestMethod.GET})
    public QResultDto getUserNameList(@RequestParam(defaultValue = "") String q,
                                      @RequestParam(defaultValue = "userName") String sortName,
                                      @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                      @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) throws BizException {

        q= StringUtils.replaceSqlPattern(q);
        return csrWorkOrderSchemaService.getCustomerList(q, pageIndex, pageSize, sortName, isAsc, null);
    }
}
